using B.S.XZYData.Api.Wrter.Application.Command.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Route
{
    /// <summary>
    /// 批量删除工艺路线处理器
    /// </summary>
    public class BatchDeleteRouteHandler : IRequestHandler<BatchDeleteRouteCommand, ApiResult<BatchDeleteRouteResult>>
    {
        private readonly IBaseRepository<RouteModel> _routeRepository;
        private readonly IBaseRepository<RouteStepModel> _routeStepRepository;
        private readonly ILogger<BatchDeleteRouteHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public BatchDeleteRouteHandler(
            IBaseRepository<RouteModel> routeRepository,
            IBaseRepository<RouteStepModel> routeStepRepository,
            ILogger<BatchDeleteRouteHandler> logger)
        {
            _routeRepository = routeRepository;
            _routeStepRepository = routeStepRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除工艺路线命令
        /// </summary>
        public async Task<ApiResult<BatchDeleteRouteResult>> Handle(BatchDeleteRouteCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.RouteIds == null || !request.RouteIds.Any())
                {
                    return new ApiResult<BatchDeleteRouteResult> 
                    { 
                        Msg = "请提供要删除的工艺路线ID", 
                        Code = ApiEnum.Fail, 
                        Data = new BatchDeleteRouteResult() 
                    };
                }

                var result = new BatchDeleteRouteResult
                {
                    TotalCount = request.RouteIds.Count
                };

                // 获取所有要删除的工艺路线
                var existingRoutes = _routeRepository.GetAll()
                    .Where(x => request.RouteIds.Contains(x.Id))
                    .ToList();

                // 检查不存在的路线ID
                var notFoundRouteIds = request.RouteIds.Except(existingRoutes.Select(x => x.Id)).ToList();
                foreach (var notFoundId in notFoundRouteIds)
                {
                    result.FailedRoutes.Add(new FailedRouteInfo
                    {
                        RouteId = notFoundId,
                        Reason = "工艺路线不存在"
                    });
                }

                // 检查每个路线是否有关联的工序
                var routesToDelete = new List<RouteModel>();
                
                foreach (var route in existingRoutes)
                {
                    var hasSteps = _routeStepRepository.GetAll()
                        .Any(x => x.RouteId == route.Id);

                    if (hasSteps)
                    {
                        result.FailedRoutes.Add(new FailedRouteInfo
                        {
                            RouteId = route.Id,
                            Reason = "工艺路线存在关联工序，不能删除"
                        });
                    }
                    else
                    {
                        routesToDelete.Add(route);
                    }
                }

                // 执行批量删除没有工序的路线
                if (routesToDelete.Any())
                {
                    await _routeRepository.DeleteBatchAsync(routesToDelete);
                    result.SuccessRouteIds = routesToDelete.Select(x => x.Id).ToList();
                }

                // 统计结果
                result.SuccessCount = result.SuccessRouteIds.Count;
                result.FailedCount = result.FailedRoutes.Count;

                // 记录日志
                if (result.SuccessCount > 0)
                {
                    _logger.LogInformation($"批量删除工艺路线部分成功，成功删除数量: {result.SuccessCount}, 成功的路线IDs: [{string.Join(", ", result.SuccessRouteIds)}], OperateBy: {request.OperateBy}");
                }

                if (result.FailedCount > 0)
                {
                    var failedInfo = string.Join("; ", result.FailedRoutes.Select(f => $"ID:{f.RouteId}-原因:{f.Reason}"));
                    _logger.LogWarning($"批量删除工艺路线部分失败，失败数量: {result.FailedCount}, 失败信息: [{failedInfo}]");
                }

                // 构造返回消息
                string message;
                ApiEnum code;

                if (result.SuccessCount == result.TotalCount)
                {
                    message = $"成功删除全部 {result.SuccessCount} 个工艺路线";
                    code = ApiEnum.Success;
                }
                else if (result.SuccessCount > 0)
                {
                    message = $"部分成功：成功删除 {result.SuccessCount} 个，失败 {result.FailedCount} 个工艺路线";
                    code = ApiEnum.Success;
                }
                else
                {
                    message = $"删除失败：全部 {result.FailedCount} 个工艺路线都无法删除";
                    code = ApiEnum.Fail;
                }

                return new ApiResult<BatchDeleteRouteResult>
                {
                    Msg = message,
                    Code = code,
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量删除工艺路线失败，路线IDs: [{string.Join(", ", request.RouteIds)}]");
                return new ApiResult<BatchDeleteRouteResult> 
                { 
                    Msg = "批量删除工艺路线失败", 
                    Code = ApiEnum.Fail, 
                    Data = new BatchDeleteRouteResult { TotalCount = request.RouteIds?.Count ?? 0 }
                };
            }
        }
    }
} 